import os

from django.http import HttpResponse, FileResponse
from django.shortcuts import render
from django.utils.http import urlquote
from rest_framework import request,status
from rest_framework.generics import ListCreateAPIView
from rest_framework.views import APIView,Response
from myapp.models import *
from myapp.views import MyPagination
from myapp.serializer import UserSer
from payroll.serializer import *
from utils.force_login import check_login


# 用户
from utils.login_util import operation_log


class UserAPIView(APIView):
    def get(self,request):
        user=UserModel.objects.filter(logic_del=0).all()
        user_ser = UserSer(user,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':user_ser})
# 工资条
class SalaryAPIView(ListCreateAPIView):
    queryset = Salary.objects.filter(logic_del=0).all()
    serializer_class = SalarySer
    pagination_class = MyPagination

    @check_login
    def post(self,request):
        user = request.session.get('user')
        uid = user['user_id']
        gate = request.data.get('days')
        absent = request.data.get('miner_days')
        leave = request.data.get('leave_days')
        base_money = request.data.get('basic_salary')
        station_money = request.data.get('post_salary')

        if not all([uid,gate,absent,leave,base_money,station_money]):
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'数据不完整'})
        Salary.objects.create(user_id=uid,gate=gate,absent=absent,leave=leave,base_money=base_money,station_money=station_money)
        operation_log(request, '添加工资条')
        return Response({'code':status.HTTP_200_OK,'msg':'添加工资条成功'})

# 单个工资条
class SalaryAPI(APIView):
    @check_login
    def get(self, requesr,pk):
        salary = Salary.objects.filter(id=pk,logic_del=0).first()
        salary_ser = SalarySer(salary, many=True).data
        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': salary_ser})

    def delete(self,request,pk):
        salary = Salary.objects.filter(id=pk, logic_del=0)
        if salary:
            salary.update(logic_del = 1)
            operation_log(request, '删除了一个工资条')
            return Response({'code': status.HTTP_200_OK, 'msg': '删除成功'})
        else:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'没有该工资条'})

    @check_login
    def put(self, request,pk):
        user = request.session.get('user')
        uid = user['user_id']
        gate = request.data.get('days')
        absent = request.data.get('miner_days')
        leave = request.data.get('leave_days')
        base_money = request.data.get('basic_salary')
        station_money = request.data.get('post_salary')

        if not all([user, gate, absent, leave, base_money, station_money]):
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '数据不完整'})
        Salary.objects.filter(id=pk).update(user_id=uid, gate=gate, absent=absent, leave=leave, base_money=base_money,
                              station_money=station_money)
        operation_log(request, '修改了一个工资条信息')
        return Response({'code': status.HTTP_200_OK, 'msg': '修改工资条成功'})

# 工资条模糊查询
class SalaryVauge(APIView):
    @check_login
    def post(self, request):
        user_name = request.data.get('user_name')
        user = UserModel.objects.get(username__contains=user_name)
        print('>>>>>>>',user)
        salary = Salary.objects.filter(user__id__contains=user.id).all()
        salary_ser = SalarySer(salary, many=True).data
        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': salary_ser})

# 审批类型
class ApplyTypeAPIView(APIView):
    queryset = ApplyTypeModel.objects.filter(logic_del=0).all()
    serializer_class = ApplyTyoeSer
    pagination_class = MyPagination

    @check_login
    def post(self,request):
        user = request.session.get('user')
        uid = user['user_id']
        name = request.data.get('name')
        comment = request.data.get('comment')

        if not all([user,name,comment]):
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'信息不完整'})

        apply = ApplyTypeModel.objects.filter(name=name)
        if apply:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该类型已存在'})
        apply.create(name=name,user_id=uid,comment=comment)
        operation_log(request, '添加了一个审批类型')
        return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})

# 单个审批类型
class ApplyTypeAPI(APIView):
    def get(self,request,pk):
        applytype = ApplyTypeModel.objects.filter(id=pk,logic_del=0)
        applytype_ser = ApplyTyoeSer(applytype).data
        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': applytype_ser})

    def put(self,request,pk):
        user = request.session.get('user')
        uid = user['user_id']
        name = request.data.get('name')
        comment = request.data.get('comment')

        if not all([user, name, comment]):
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '信息不完整'})

        apply = ApplyTypeModel.objects.filter(id=pk,logic_de=0)
        if apply:
            apply.update(name=name, user_id=uid, comment=comment)
            operation_log(request, '修改了一个审批类型')
            return Response({'code': status.HTTP_200_OK, 'msg': '修改成功'})
        return Response({"code": status.HTTP_400_BAD_REQUEST, 'msg': '该类型不存在'})

    def delete(self,reqeust,pk):
        apply = ApplyTypeModel.objects.filter(id=pk,logic_de=0)
        if apply:
            apply.update(logic_del=1)
            operation_log(request, '删除了一个审批类型')
            return Response({"code":status.HTTP_200_OK,'msg':'删除成功'})
        return Response({"code":status.HTTP_400_BAD_REQUEST,'msg':'该类型不存在'})

# 审批流程
class FlowAPIView(APIView):
    def get(self,request):
        flow = FlowModel.objects.filter(logic_del=0).all()
        flow_ser = FlowSer(flow,many=True).data
        for i in flow_ser:
            print(i['apply'])
            approver= ApproverModel.objects.filter(apply_id=i['apply']).all()
            approver_ser = ApproverSer(approver,many=True).data
            approverlist = []
            i['approval_process'] = approverlist
            for j in approver_ser:
                approverlist.append(j['user_name'])
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':flow_ser})

    def post(self,request):
        apply = request.data.get('apply')
        state = request.data.get('state')
        process_title = request.data.get('process_title')
        jurisdiction = request.data.get('jurisdiction')
        s = jurisdiction[1:-1]
        s1 = s.split(',')
        if not all([apply, process_title,state]):
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '数据不完整'})

        FlowModel.objects.create(apply_id=apply, process_title=process_title,state=state)
        for i in s1:
            ApproverModel.objects.create(apply_id=apply, user_id=i)
        operation_log(request,'添加了一个审批流程')
        return Response({'code': status.HTTP_200_OK, 'msg': '添加成功'})

# 单个审批流程
class FlowAPI(APIView):
    def get(self, request,pk):
        flow = FlowModel.objects.filter(id=pk,logic_del=0).all()
        flow_ser = FlowSer(flow, many=True).data
        for i in flow_ser:
            print(i['apply'])
            approver = ApproverModel.objects.filter(apply_id=i['apply']).all()
            approver_ser = ApproverSer(approver, many=True).data
            approverlist = []
            i['approval_process'] = approverlist
            for j in approver_ser:
                approverlist.append(j['user_name'])
        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': flow_ser})

    def put(self,request,pk):
        apply = request.data.get('apply')
        state = request.data.get('state')
        process_title = request.data.get('process_title')
        jurisdiction = request.data.get('jurisdiction')

        s = jurisdiction[1:-1]
        s1 = s.split(',')
        if not all([apply, process_title, state]):
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '数据不完整'})

        FlowModel.objects.filter(id=pk).update(apply_id=apply, process_title=process_title, state=state)
        for i in s1:
            ApproverModel.objects.update(apply_id=apply, user_id=i)
        operation_log(request, '修改了一个审批流程')
        return Response({'code': status.HTTP_200_OK, 'msg': '修改成功'})


class Upload_file(APIView):
    def post(self,request):
        myFile =request.FILES.get("myfile", None)  # 获取上传的文件，如果没有文件，则默认为None
        if not myFile:
          return Response({"code":status.HTTP_400_BAD_REQUEST,'msg':'没有选择文件'})
        mater = MaterialManageModel.objects.filter(m_name = myFile.name)
        if mater:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'文件已存在'})
        destination = open(os.path.join("D:\pythondjango",myFile.name),'wb+')  # 打开特定的文件进行二进制的写操作
        for chunk in myFile.chunks():   # 分块写入文件
          destination.write(chunk)
        destination.close()
        print('>>>>',destination.name)
        # 存入数据库
        MaterialManageModel.objects.create(m_name = myFile.name,m_route = destination.name)
        return Response({'code':status.HTTP_200_OK,'msg':'上传成功','url':destination.name})

    def get(self,request):
        mater = MaterialManageModel.objects.all()
        mater_ser = MaterialSer(mater,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':mater_ser})

class MaterialAPI(APIView):
    def get(self,request,pk):
        file_info = MaterialManageModel.objects.get(id=pk)
        print('下载的文件名：' + file_info.m_name)
        response = FileResponse(open(file_info.m_route, 'rb'))
        response['content_type'] = "application/octet-stream"
        response['Content-Disposition'] = 'attachment;filename=' + os.path.basename(file_info.m_route)
        return response








